# -*- coding: utf-8 -*
from flask import Flask, request, jsonify, send_from_directory
from paddleocr import PaddleOCR, draw_ocr
import os

def get_text_positioning(img_path):
    ocr = PaddleOCR(use_angle_cls=True, lang="ch")  
    result = ocr.ocr(img_path, cls=True)
    backdata = []
    for idx in range(len(result)):
        res = result[idx]
        for line in res:
            backdata.append(line)
    return backdata
    
app = Flask(__name__)


# 允许上传的文件格式
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

class ImageUploader:
    def upload(self):
        if 'file' not in request.files:
            return jsonify({'error': 'No file part'}), 400
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': 'No selected file'}), 400
        if file and allowed_file(file.filename):
            filename = file.filename
            file_path = filename
            file.save(file_path)
                  
            res = get_text_positioning(file_path)
            # 删除file_path文件
            os.remove(file_path)
            return jsonify({'code': 201, 'message': '文件识别成功', 'data': res}), 201
        else:
            return jsonify({'code': '400', 'message': 'File type not allowed'}), 400

@app.route('/upload', methods=['POST'])
def upload_file():
    uploader = ImageUploader()
    return uploader.upload()
# 首页路由，返回upload.html文件
@app.route('/')
def index():
    return send_from_directory(os.path.abspath(os.path.dirname(__name__)), 'upload.html')
    
    
if __name__ == '__main__':
    app.config['JSON_AS_ASCII'] = False 
    #app.run(debug=True)
    app.run(host='0.0.0.0', port=5000,use_reloader=False, use_debugger=False)
